package com.weaver.qfengx;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.google.common.io.ByteStreams;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

/**
 * servlet 相关操作工具类
 * @Author Opp
 * @Date 2023-02-14 09:55
 */
public class HttpServletUtils {

    public static void respToJson(Object data, HttpServletResponse response) {
        try {
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().print(JSON.toJSONString(data));
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    public static String getClientIp(HttpServletRequest request) {
        try {
            String ip = request.getHeader("X-Real-IP");
            String xff = request.getHeader("X-Forwarded-For");
            if (StringUtils.isNotEmpty(xff) && !"unKnown".equalsIgnoreCase(xff)) {
                // 多次反向代理后会有多个ip值，第一个ip才是真实ip
                int index = xff.indexOf(",");
                if (index != -1) {
                    return xff.substring(0, index);
                } else {
                    return xff;
                }
            }
            xff = ip;
            if (StringUtils.isNotEmpty(xff) && !"unKnown".equalsIgnoreCase(xff)) {
                return xff;
            }
            if (StringUtils.isBlank(xff) || "unknown".equalsIgnoreCase(xff)) {
                xff = request.getHeader("Proxy-Client-IP");
            }
            if (StringUtils.isBlank(xff) || "unknown".equalsIgnoreCase(xff)) {
                xff = request.getHeader("WL-Proxy-Client-IP");
            }
            if (StringUtils.isBlank(xff) || "unknown".equalsIgnoreCase(xff)) {
                xff = request.getHeader("HTTP_CLIENT_IP");
            }
            if (StringUtils.isBlank(xff) || "unknown".equalsIgnoreCase(xff)) {
                xff = request.getHeader("HTTP_X_FORWARDED_FOR");
            }
            if (StringUtils.isBlank(xff) || "unknown".equalsIgnoreCase(xff)) {
                xff = request.getRemoteAddr();
            }
            return xff;
        } catch (Exception e) {
            return "";
        }
    }

    /**
     * 下载文件名
     * @param request
     */
    public static boolean transfer(File file, HttpServletRequest request,
                                   HttpServletResponse response) {
        try {
            return transfer(file.getName(), new FileInputStream(file), request, response);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public static boolean transfer(String filename, InputStream inputStream, HttpServletRequest request,
                                   HttpServletResponse response) {
        try {
            String userAgent = request.getHeader("User-Agent");
            if (StrUtil.isNotBlank(userAgent) && (userAgent.toUpperCase().contains("MSIE") || userAgent.toUpperCase().contains("TRIDENT"))) //针对IE或IE为内核的浏览器
                filename = java.net.URLEncoder.encode(filename, "UTF-8");
            else
                filename = new String(filename.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);//谷歌控制版本
            response.setContentType("application/octet-stream");
            response.addHeader("Content-Disposition", "attachment;filename=" + filename);
            ByteStreams.copy(inputStream, response.getOutputStream());
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

}
